Skip to content

Implement readonly modifier for classes - #138

Merged
thekid merged 5 commits into
masterfrom
feature/readonly_classes
May 14, 2022
Merged

Implement readonly modifier for classes#138
thekid merged 5 commits into
masterfrom
feature/readonly_classes

Conversation

@thekid

@thekid thekid commented May 6, 2022

Copy link
Copy Markdown
Member

See https://wiki.php.net/rfc/readonly_classes and xp-framework/ast#37. The following comes quite close to records, although it doesn't declare getters but uses public readonly fields:

readonly class Point {
  public function __construct(
    public int $x,
    public int $y,
  ) { }
}

$point= new Point(8, 42);
echo "Hello {$point->x}x{$point->y}!\n";

// Will not modify the member, raising an exception instead:
// $point->x= 9;
  • Inherit readonly modifiers on classes to all members and promoted constructor parameters
  • Prevent dynamic members
  • Do not allow readonly on traits, interfaces and enums
  • Prevent inheritance where readonly modifiers do not match
  • Prevent static members in readonly classes
  • Disallow #[AllowDynamicProperties] on readonly classes
  • Remove emulation for PHP 8.2 once Add support for readonly classes php/php-src#7305 is merged

}

#[Test, Ignore('Until proper error handling facilities exist')]
public function readonly_classes_cannot_have_static_members() {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This proper error handling means any way of raising an exception from within the emitting phase and having it turned into a lang.ast.Error with file and line set.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe these also need to go into the parser - where, instead of returning lang.ast.Node instances directly, we'd do something like:

// Before
return new PropertyNode(...);

// After
return $this->ast->property(...);

...and have two separate ast implementations: checked and unchecked. This would be part of a greater refactoring, thus keeping it for a separate pull request.

@thekid
thekid merged commit dcc404e into master May 14, 2022
@thekid
thekid deleted the feature/readonly_classes branch May 14, 2022 15:08
@thekid

thekid commented May 14, 2022

Copy link
Copy Markdown
Member Author

Released in https://github.com/xp-framework/compiler/releases/tag/v8.4.0 - removing the emulation from PHP 8.2 emitter can be done once the php-src PR is merged, and released in a separate release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant